package framework.captcha;

import framework.exceptions.ConfigurationException;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.cache.Cache;
import org.springframework.util.StringUtils;

public class CaptchaBase implements Captcha {

    @Getter
    private Cache cache;

    @Getter
    private CaptchaGenerator generator;

    @Setter
    @Getter
    private Boolean ignoreCase = true;

    public CaptchaBase(Cache cache) {
        this.generator = new CaptchaGenerator();
        this.cache = cache;
    }

    public CaptchaBase(Cache cache, CaptchaGenerator generator) {
        this.generator = generator;
        this.cache = cache;
    }

    @Override
    public CaptchaInfo newCaptcha(String id) {
        CaptchaInfo captchaInfo = getGenerator().generate();
        getCache().put(this.buildKey(id), captchaInfo.getCode());
        return captchaInfo;
    }

    @SneakyThrows
    @Override
    public boolean check(String id, String code) {
        if (!StringUtils.hasLength(id)) {
            return false;
        }
        if (!StringUtils.hasText(code)) {
            return false;
        }

        //
        if (getCache() == null) {
            throw new ConfigurationException("not set cache");
        }

        //
        String s = getCache().get(this.buildKey(id), String.class);
        boolean r = this.getIgnoreCase() ? code.equalsIgnoreCase(s) : code.equals(s);

        //
        return r;
    }

    @Override
    public void remove(String id) {
        if (this.getCache() != null) {
            this.getCache().evict(this.buildKey(id));
        }
    }

    protected String buildKey(String id) {
        return "captcha:" + id;
    }

}
